package android.pot.com.smartcar.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.base.swipe.SwipeBackActivity;
import android.pot.com.smartcar.tool.LoadingTool;
import android.pot.com.smartcar.tool.TipToast;
import android.pot.com.smartcar.util.NetUtil;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;


public class UserShowWebView extends SwipeBackActivity implements OnClickListener,View.OnTouchListener {

    private TextView tv_title;
    private WebView webview;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    LoadingTool.EndLoading(UserShowWebView.this);

                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_show_vebview);
        initView();
        setView();
        addListener();

    }


    private void setView() {
        if (NetUtil.checkNet(this)) {
            LoadingTool.StartLoading(this);
            Bundle bundle = getIntent().getExtras();
            String url = bundle.getString("URL");
            ShowWV(webview, url);
            handler.sendEmptyMessage(0);
        }
    }

    @Override
    protected void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_webview);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        webview = new WebView(this);
        webview.setLayoutParams(params);
        webview.setOverScrollMode(View.OVER_SCROLL_NEVER);
        webview.setOnTouchListener(this);

        //设置自适应屏幕，两者合用
        webview.getSettings().setUseWideViewPort(true); //将图片调整到适合webview的大小
        webview.getSettings().setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        webview.getSettings().setSupportZoom(true);
        webview.getSettings().setBuiltInZoomControls(true);
        //隐藏缩放工具
        webview.getSettings().setDisplayZoomControls(false);

        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webview.getSettings().setLoadsImagesAutomatically(true); //支持自动加载图片
        webview.getSettings().setDefaultTextEncodingName("utf-8");//设置编码格式
        // 添加javaScript支持
        webview.getSettings().setJavaScriptEnabled(true);
        webview.removeJavascriptInterface("searchBoxJavaBridge_");
        mainLayout.addView(webview);

    }

    @Override
    protected void initData() {

    }


    @Override
    protected void addListener() {
        findViewById(R.id.img_back).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                if (webview.canGoBack()) {
                    webview.goBack();
                } else {
                    scrollToFinishActivity();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                scrollToFinishActivity();
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void ShowWV(final WebView webview, String url) {
        // WebView加载web资源
        webview.setWebChromeClient(new WebChromeClient() {
                                       @Override
                                       public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
                                           AlertDialog.Builder b = new AlertDialog.Builder(UserShowWebView.this);
                                           b.setTitle("Alert");
                                           b.setMessage(message);
                                           b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                               @Override
                                               public void onClick(DialogInterface dialog, int which) {
                                                   result.confirm();
                                               }
                                           });
                                           b.setCancelable(false);
                                           b.create().show();
                                           return true;
                                       }

                                       public boolean onJsConfirm(WebView view, String url, String message, final android.webkit.JsResult result) {

                                           AlertDialog.Builder b = new AlertDialog.Builder(UserShowWebView.this);
                                           b.setTitle("Confirm");
                                           b.setMessage(message);
                                           b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                               @Override
                                               public void onClick(DialogInterface dialog, int which) {
                                                   result.confirm();
                                               }
                                           });
                                           b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                                               @Override
                                               public void onClick(DialogInterface dialog, int which) {
                                                   result.cancel();
                                               }
                                           });
                                           b.create().show();
                                           return true;
                                       }

                                       ;

                                       @Override
                                       public void onReceivedTitle(WebView view, String title) {
                                           tv_title.setText(title);
                                       }
                                   }
        );
        // 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webview.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                switch (errorCode) {

                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();    //表示等待证书响应
                TipToast.show(error.toString());
                // handler.cancel();      //表示挂起连接，为默认方式
                // handler.handleMessage(null);    //可做其他处理
            }
        });
        webview.loadUrl(url);

    }

    @Override
    public void onDestroy() {
        if (webview != null) {
            webview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webview.clearHistory();
            ((ViewGroup) webview.getParent()).removeView(webview);
            webview.destroy();
            webview = null;
        }
        super.onDestroy();

    }

    private float OldX1,OldY1,OldX2,OldY2,NewX1,NewY1,NewX2,NewY2;
    @Override
        public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                case MotionEvent.ACTION_POINTER_2_DOWN:
                        if (event.getPointerCount() == 2) {
                                for (int i = 0; i < event.getPointerCount(); i++) {
                                        if (i == 0) {
                                                OldX1 = event.getX(i);
                                                OldY1 = event.getY(i);
                                        } else if (i == 1) {
                                                OldX2 = event.getX(i);
                                                OldY2 = event.getY(i);
                                        }
                                }
                        }
                        break;
                case MotionEvent.ACTION_MOVE:
                        if (event.getPointerCount() == 2) {
                                for (int i = 0; i < event.getPointerCount(); i++) {
                                        if (i == 0) {
                                                NewX1 = event.getX(i);
                                                NewY1 = event.getY(i);
                                        } else if (i == 1) {
                                                NewX2 = event.getX(i);
                                                NewY2 = event.getY(i);
                                        }
                                }
                                float disOld = (float) Math.sqrt((Math.pow(OldX2 - OldX1, 2) + Math.pow(
                                                OldY2 - OldY1, 2)));
                                float disNew = (float) Math.sqrt((Math.pow(NewX2 - NewX1, 2) + Math.pow(
                                                NewY2 - NewY1, 2)));
                                if (disOld - disNew >= 25) {
                                        // 缩小
                                        webview.zoomOut();

                                } else if(disNew - disOld >= 25){
                                        // 放大
                                    webview.zoomIn();
                                }
                                OldX1 = NewX1;
                                OldX2 = NewX2;
                                OldY1 = NewY1;
                                OldY2 = NewY2;
                        }
                }

                return false;
        }

}
